import Cookies from 'js-cookie'
import { tokenKey } from '@/config/settings'
import settings from '@/config/settings'

const keyByPre = (key) => {
    key = settings.appId + key
    return key
}

export function getToken() {
    const key = keyByPre(tokenKey)
    return Cookies.get(key)
}

export function setToken(token) {
    const key = keyByPre(tokenKey)
    return Cookies.set(key, token)
}

export function removeToken() {
    const key = keyByPre(tokenKey)
    return Cookies.remove(key)
}

export function redirect(target, tag, blank) {
    let token = getToken()
    const querySplit = target.includes('?') ? '&' : '?'
    token = encodeURI(token)
    token = encrypt(token)
    const path = tag ? `${target}${querySplit}_t=${token}&tag=${tag}` : `${target}${querySplit}_t=${token}`
    // 控制台进入的系统需要打开新窗口，子系统跳转的不用
    if (blank) {
        window.open(path, '_blank', 'noopener,noreferrer')
    } else {
        window.location.href = path
    }
}
// 对 url 中的 token 简单加密
const xorKey = '5432167890'
export function encrypt(data, key = xorKey) {
    const r = []
    for (let i = 0; i < data.length; i++) {
        const code = data.charCodeAt(i) ^ key.charCodeAt(i % key.length)
        r.push(code)
    }
    return r.join('-')
}

export function decrypt(data, key = xorKey) {
    let r = data.split('-')
    r = r.map(d => Number(d))
    r = r.map((m, i) => {
        const code = m ^ key.charCodeAt(i % key.length)
        const s = String.fromCharCode(code)
        return s
    })
    return r.join('')
}
